package com.xdja.kafka.hdfs.sink.thread;
import com.xdja.kafka.hdfs.sink.bean.HuaweiLoginBean;
import com.xdja.kafka.util.LoginUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 华为认证线程，每隔一定时间认证一次
 */
public class HuaweiAuthThread extends Thread{
    private static Logger log = LoggerFactory.getLogger(HuaweiAuthThread.class);
    /**
     * 线程是否被打断标志位，false:未被打断，true:被打断
     */
    private boolean interrupt = false;
    /**
     * 默认休眠时长，单位毫秒： 60分钟
     */
    private final long longSleepTime = 60 * 60 * 1000;

    private HuaweiLoginBean huaweiLoginBean;

    public HuaweiAuthThread(HuaweiLoginBean huaweiLoginBean) {
        this.huaweiLoginBean = huaweiLoginBean;
    }

    @Override
    public void run() {
        Thread.currentThread().setName("hdfs_huawei_auth_" + System.currentTimeMillis());
        //先休眠指定时长
        try {
            sleep(longSleepTime);
        } catch (InterruptedException e) {
            //外部由interrupt该线程时，若该线程刚好在休眠，会走到这里
            log.info("未进入休眠, 原因：{}", e.getCause().getMessage());
            interrupt = true;
            return;
        }
        //每隔指定时长进行认证一次
        while(!interrupt) {
            try {
                LoginUtil.login(huaweiLoginBean);
            } catch (IOException e) {
                log.error("华为云hadoop认证失败，终止本connector运行, 原因：{}", e.getMessage(), e);
            }
            try {
                sleep(longSleepTime);
            } catch (InterruptedException e) {
                //外部由interrupt该线程时，若该线程刚好在休眠，会走到这里
                log.info("未进入休眠, 原因：{}", e.getCause().getMessage());
                interrupt = true;
                return;
            }
        }
    }
}
